package cn.tedu.search.config
import java.net.InetAddress
import java.util.List

import org.elasticsearch.client.transport.TransportClient
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.common.transport.InetSocketTransportAddress
import org.elasticsearch.transport.client.PreBuiltTransportClient
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
/**
 * 创建一个框架维护的内存对象,TransportClient
 * @author admin
 *
 */
@Configuration
@ConfigurationProperties(prefix = "es")
class TransportConfig {

  private var nodes: List[String] = _

  //定义初始化transportclient的方法
  @Bean
  def initTclient: TransportClient = {
    val client = new PreBuiltTransportClient(Settings.EMPTY) //配置默认
    nodes.forEach { node =>
      try {
        //解析ip和端口,代码端口9300
        val host = node.split(":")(0)
        val port = node.split(":")(1).toInt
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port))
      } catch { case t: Throwable => t.printStackTrace()}
    }
    client
  }
  def getNodes = nodes
  def setNodes(nodes: List[String]) { this.nodes = nodes }

}
